﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfSnqkGasAnalysis.IBusiness_impl;
using WpfSnqkGasAnalysis.Model;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// WindowWaterPointAdd.xaml 的交互逻辑
    /// </summary>
    public partial class WindowWaterPointAdd : Window
    {
        public WindowWaterPointAdd()
        {
            InitializeComponent();
        }
        private long waterpointKEY = 0;

        WaterPointBusiness waterpointBusiness = new WaterPointBusiness();
        SourceDictBusiness sourceDictBusiness = new SourceDictBusiness();
        UserBusiness userBusiness = new UserBusiness();

        /// <summary>
        /// DataGrid 分页数据刷新
        /// </summary>
        internal event EventHandler DataGridRefresh;

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //禁用关闭按钮
            int handle = new WindowInteropHelper(this).Handle.ToInt32();
            WinodowCloseButtonSet.Disable(handle);

            Snowflake snowflake = new Snowflake(1, 1);
            waterpointKEY = snowflake.NextId();

            var list = sourceDictBusiness.GetAll();
            list = list.FindAll(g => g.D_stat == 1);

            var userList = userBusiness.GetAllUser();
            userList = userList.FindAll(g => g.U_stat == 1);

            //委托单位  
            cmb_Client.ItemsSource = list.FindAll(x => x.Group_id.Equals("quyang"));
            cmb_Client.DisplayMemberPath = "Item_name";
            cmb_Client.SelectedValuePath = "Id";

            //分析单位  cmb_AnalyUnit 
            cmb_AnalyUnit.ItemsSource = list.FindAll(x => x.Group_id.Equals("quyang"));
            cmb_AnalyUnit.DisplayMemberPath = "Item_name";
            cmb_AnalyUnit.SelectedValuePath = "Id";

            //取样位置
            cmb_TestLocation.ItemsSource = list.FindAll(x => x.Group_id.Equals("quyangLocation"));
            cmb_TestLocation.DisplayMemberPath = "Item_name";
            cmb_TestLocation.SelectedValuePath = "Id";

            //分析人    
            cmb_Analyst.ItemsSource = userList;
            cmb_Analyst.DisplayMemberPath = "User_real_name";
            cmb_Analyst.SelectedValuePath = "Id";
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void numberCheck_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            var textElem = (sender as TextBox);

            //解决连续输入很多.
            if ((
                textElem.Text.StartsWith(".") || string.IsNullOrWhiteSpace(textElem.Text)
                || textElem.Text.Contains(".")
                ) && e.Text == ".")
            {
                e.Handled = true;
                return;
            }

            //禁止在0前面继续输入0
            int index = ((System.Windows.Controls.TextBox)e.Source).CaretIndex;
            if (textElem.Text.StartsWith("0.") && index == 0 && e.Text == "0")
            {
                e.Handled = true;
                return;
            }

            //不能输入非数字
            if (Regex.IsMatch(e.Text, @"[^\d+\.{0,1}\d+]+"))
            {
                e.Handled = true;
                return;
            }
        }

        //检查输入字符串是否为数字 //创建时间：2022-12-7 15:16:20，作者：王浩力
        private void numberCheck_PreviewKeyUp(object sender, KeyEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (!string.IsNullOrWhiteSpace(textBox.Text))
            {
                if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
                {
                    textBox.Text = textBox.Text.Replace("00", "");
                }
                if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
                {
                    textBox.Text = textBox.Text.TrimStart('0');
                }

                //输入的不是小数或正整数           
                Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
                textBox.Text = regex.Replace(textBox.Text, "");
            }
        }

        //按Delete，删除一项
        private void listView_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                ListView listview = (ListView)sender;
                Water_point_item? item = listview.SelectedItem as Water_point_item;
                if (item == null)
                {
                    e.Handled = true;
                    return;
                }

                //执行删除
                var result = waterpointBusiness.DeleteItem(item.Id);
                ShowAlertHelpter.ShowAlert(result.Msg);
                if (result.Code == (int)ResultCode.Success)
                {
                    var list = waterpointBusiness.GetWater_point_itemList(item.WaterPointId);
                    this.listView.ItemsSource = list;
                }
            }

        }

        //继续添加
        private void waterItemAdd_Click(object sender, RoutedEventArgs e)
        {
            WindowWaterPointItemAdd itemAdd = new WindowWaterPointItemAdd();
            itemAdd.RefreashListView += ItemAdd_RefreashListView;
            itemAdd.mainKey = waterpointKEY;
            itemAdd.ShowDialog();
        }

        private void ItemAdd_RefreashListView(object? sender, EventArgs e)
        {
            var list = waterpointBusiness.GetWater_point_itemList(waterpointKEY);
            this.listView.ItemsSource = list;
        }

        //保存
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            Water_point info = new Water_point();
            info.Id = waterpointKEY;
            info.Report_no = txt_report_no.Text;
            info.Client = cmb_Client.SelectedValue.ToMyInt64();
            info.Analyst = cmb_Analyst.SelectedValue.ToMyInt64();
            info.FluTemperature = txtFluTemperature.Text.ToMyDecimal();
            info.WellAndWellNo = txt_well_no.Text;
            info.AirSource = txt_AirSource.Text;
            info.Analytime = date_Analytime.Text;
            info.AnalyUnit = cmb_AnalyUnit.SelectedValue.ToMyInt64();

            //测试位置  //修改时间：2023-1-15 21:41:27。
            string _testLocation = cmb_TestLocation.SelectedValue?.ToString();
            if (!string.IsNullOrWhiteSpace(txt_TestLocation2.Text))
            {
                _testLocation = txt_TestLocation2.Text.Trim();
            }
            info.TestLocation = _testLocation;

            //温度保留1位小数。修改时间：2023-1-30 10:56:13。
            if (!string.IsNullOrWhiteSpace(txt_AmbientTemperature.Text))
            {
                info.AmbientTemperature = Math.Round(txt_AmbientTemperature.Text.ToMyDecimal2(), 1);
            }

            var result = waterpointBusiness.Add(info);
            ShowAlertHelpter.ShowAlert(result.Msg);
            if (result.Code == (int)ResultCode.Success)
            {
                DataGridRefresh?.Invoke(this, e);
                this.listView.ItemsSource = null;

                //没点击一次。就刷新一次waterpointKEY
                Snowflake snowflake = new Snowflake(1, 1);
                waterpointKEY = snowflake.NextId();
            }
            //this.Close();
        }

        //退出
        private void Exit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }


    }
}
